package com.edushare.activity;

import java.io.File;
import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.edushare.R;
import com.edushare.controller.HttpUploader;
import com.samsung.sdraw.SDrawLibrary;

public class IconMenu extends Activity {
	public static final String LOG_TAG = "UnifiqDraw";
	public static final String PICTURE_FILE_ID = "picture";
	public static final String TMP_FILE_NAME = ".unifiq";
	private static final int CAMERA_REQUEST_CODE = 666;
	private static final int GALLERY_REQUEST_CODE = 777;
	private File mPictureFile;

	/**
	 * Listener for clicking "take picture" button.
	 */
	private final OnClickListener mTakePictureListener = new OnClickListener() {
		@Override
		public void onClick(final View arg0) {
			takePicture();
		}
	};

	/**
	 * Listener for clicking "load picture" button.
	 */
	private final OnClickListener mLoadPictureListener = new OnClickListener() {
		@Override
		public void onClick(final View arg0) {
			loadPicture();
		}
	};

	/**
	 * Listener for clicking "change picture" button
	 */
	private final OnClickListener mUploadPictureListener = new OnClickListener() {
		@Override
		public void onClick(final View arg0) {
			replacePicture();
		}
	};

	/**
	 * Prevents from running this application on an unsupported device.
	 */
	private void checkIfDeviceSupported() {
		if (!SDrawLibrary.isSupportedModel()) {
			Toast.makeText(this, "This feature runs only on Spen Devices",
					Toast.LENGTH_SHORT).show();
			finish();
		}
	}

	/**
	 * Starts draw activity with given background.
	 */
	private void draw() {
		if (mPictureFile != null) {
			Intent intent = new Intent(this, DrawActivity.class);
			intent.putExtra(PICTURE_FILE_ID, mPictureFile);
			startActivity(intent);
		}
	}

	/**
	 * Gets application temporary file handler.
	 * 
	 * @return Handler to file on an external storage
	 */
	private File getFile() {
		return new File(getExternalFilesDir(null), TMP_FILE_NAME);
	}

	/**
	 * Gets path of an image from the gallery.
	 * 
	 * @param uri
	 *            Image Uri
	 * @return Image absolute path
	 */
	private String getImagePath(final Uri uri) {
		String[] projection = { MediaColumns.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	private String getRealPathFromURI(Uri contentUri) {

		String[] proj = { MediaColumns.DATA };
		android.database.Cursor cursor = managedQuery(contentUri, proj, // Which
																		// columns
																		// to
																		// return
				null, // WHERE clause; which rows to return (all rows)
				null, // WHERE clause selection arguments (none)
				null); // Order-by clause (ascending by name)
		int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	/**
	 * Initializes all visible buttons.
	 */
	private void initButtons() {
		// Button takePictureButton = (Button)
		// findViewById(R.id.take_picture_btn);
		// takePictureButton.setTypeface(Typeface.createFromAsset(getAssets(),
		// "fonts/Roboto-Regular.ttf"));
		// takePictureButton.setOnClickListener(mTakePictureListener);
		Button loadPictureButton = (Button) findViewById(R.id.load_picture_btn);
		Button uploadButton = (Button) findViewById(R.id.gallery_btn);
		loadPictureButton.setTypeface(Typeface.createFromAsset(getAssets(),
				"fonts/Roboto-Regular.ttf"));
		loadPictureButton.setOnClickListener(mLoadPictureListener);
		uploadButton.setOnClickListener(mUploadPictureListener);
	}

	/**
	 * Starts an activity for loading a picture.
	 */
	private void loadPicture() {
		Intent intent = new Intent(Intent.ACTION_PICK,
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(intent, GALLERY_REQUEST_CODE);
	}

	@Override
	protected void onActivityResult(final int requestCode,
			final int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// if (resultCode == RESULT_OK) {
		switch (requestCode) {
		case CAMERA_REQUEST_CODE:
			draw();
			break;
		case GALLERY_REQUEST_CODE:
			mPictureFile = new File(getImagePath(data.getData()));
			draw();
			break;
		case 1:
			// currImageURI is the global variable I'm using to hold the
			// content:
			Uri currImageURI = data.getData();
			System.out.println("Current image Path is "
					+ getRealPathFromURI(currImageURI));

			HttpUploader uploader = new HttpUploader();
			try {
				String imagename = uploader.execute(
						getRealPathFromURI(currImageURI)).get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}

			break;
		default:
			break;
		}
		// }
	}

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.iconmenu);

		// checkIfDeviceSupported();
		initButtons();
	}

	// Convert the image URI to the direct file system path of the image file

	/**
	 * Starts an activity for replacing picture
	 */
	private void replacePicture() {
		// To open up a gallery browser
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent, "Select Picture"),
				1);
	}

	/**
	 * Starts an activity for taking a picture.
	 */
	private void takePicture() {
		mPictureFile = getFile();
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPictureFile));
		startActivityForResult(intent, CAMERA_REQUEST_CODE);
	}
}